package cn.tedu.tmall.front.mall.dao.repository.impl;

import cn.tedu.tmall.common.pojo.po.MallCacheCategoryPO;
import cn.tedu.tmall.common.pojo.vo.MallCategoryTreeVO;
import cn.tedu.tmall.front.mall.dao.repository.ICategoryCacheRepository;
import cn.tedu.tmall.front.mall.pojo.po.CategoryPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
//@SuppressWarnings("unchecked")
public class CategoryCacheRepository implements ICategoryCacheRepository {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void saveCategoryTree(List<MallCategoryTreeVO> mallCategoryTreeVOS) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("ALL", mallCategoryTreeVOS);
    }

    @Override
    public List<MallCategoryTreeVO> getCategoryTree() {
        ValueOperations<String, List<MallCategoryTreeVO>> valueOperations = redisTemplate.opsForValue();
        return valueOperations.get("ALL");
    }

    @Override
    public List<MallCacheCategoryPO> getTopCategory() {
        return getChildrenCategory(0L);
    }

    @Override
    public void saveCategory(List<MallCacheCategoryPO> dbTopCategoryPOS) {
        saveChildrenCategory(0L, dbTopCategoryPOS);
    }

    @Override
    public List<MallCacheCategoryPO> getChildrenCategory(Long parentId) {
        ListOperations<String, MallCacheCategoryPO> listOperations = redisTemplate.opsForList();
        String key = "mall_category_by_parent_id_" + parentId;
        return listOperations.range(key, 0, -1);
    }

    @Override
    public void saveChildrenCategory(Long parentId, List<MallCacheCategoryPO> dbChildrenCategoryPOS) {
        ListOperations listOperations = redisTemplate.opsForList();
        String key = "MALL_CATEGORY_BY_PARENT_ID_" + parentId ;
        for (MallCacheCategoryPO cacheCategoryPO : dbChildrenCategoryPOS) {
            //todo 时间格式暂时序列化失败,不解决,先设置为空
            listOperations.rightPush(key,cacheCategoryPO);
        }
    }

}
